package sundun.sharding.execution.impl;


import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sundun.sharding.config.TableConfiguration;
import sundun.sharding.factory.SqlSessionFactoryWrapper;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * insert delete update
 * @author: zxl
 * @date: 2024/8/11 10:20
 */
public class WriteExecutionStrategy extends AbstractExecutionStrategy{
    private static final Logger logger = LoggerFactory.getLogger(WriteExecutionStrategy.class);


    public WriteExecutionStrategy(SqlSessionFactoryWrapper sqlSessionFactoryWrapper, Map<String, TableConfiguration> tableConfigurations) {
        super(sqlSessionFactoryWrapper, tableConfigurations);
    }


    @Override
    protected Object doExecute(Invocation invocation, TableConfiguration tableRule, MetaObject metaStatementHandler, MappedStatement mappedStatement) throws InvocationTargetException, IllegalAccessException {

        Object proceed = invocation.proceed();
        if (tableRule.getBothWriter()){
            try {
                //执行双写 如果配置异步 开启线程处理
                Object res = invoke(invocation,metaStatementHandler,mappedStatement);
                logger.info("【切换原库】-{write}-插入数据至原数据库表! ");
            }catch (Exception e){
                logger.error("both write exception",e);
                throw new RuntimeException("main table write exception ",e);
            }

        }

        return proceed;
    }

}
